package com.ruoyi.project.product.url.controller;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.product.url.domain.Url;
import com.ruoyi.project.product.url.service.IUrlService;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * 产品系列操作处理
 *
 * @author Mai
 */
@Controller
@RequestMapping("product/url")
public class UrlController extends BaseController {

    private String prefix = "product/url";

    @Autowired
    private IUrlService urlService;

    /**
     * 跳转到查询页面
     *
     * @return
     */
    @GetMapping()
    @RequiresPermissions("product:url:view")
    public String url() {
        return prefix + "/url";
    }

    /**
     * 图库系列查询
     *
     * @param url
     * @return
     */
    @ResponseBody
    @PostMapping("/list")
    @RequiresPermissions("product:url:list")
    public TableDataInfo list(Url url) {
        startPage();
        List<Url> list = urlService.selectUrlList(url);
        return getDataTable(list);
    }


    /**
     * 系列批量删除操作
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @PostMapping("/remove")
    @RequiresPermissions("product:url:remove")
    public AjaxResult remove(String ids) {
        try {
            return toAjax(urlService.deleteUrlByIds(ids));
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    @GetMapping("/add")
    public String add(){
        return prefix + "/add";
    }

/**
     * 保存文件，直接以multipartFile形式
     * @param
     * @return 返回文件名
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/add")
    @RequiresPermissions("product:url:add")
    public AjaxResult addSave(MultipartFile file){
//        String path = System.getProperty("user.dir")+"/src/main/resources/static/img";

        String path2 = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/img";

        File file2 = new File(path2);

        if (!file2.exists()) {
            file2.mkdirs();
        }

        String fileName = UUID.randomUUID().toString().replaceAll("-","");

        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        String newFileName= fileName + "." + extension;


        File f2 = new File(file2, newFileName);
        System.out.println(f2);
        try{
            file.transferTo(f2);
        }catch (IOException e){
            e.printStackTrace();
        }

        return toAjax(urlService.insertUrl(newFileName));
    }

}
